﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Windows;

namespace Kokomo
{
	public static class DispatcherExtensions
	{
		public static TObject Instantiate<TObject>(this Dispatcher dispatcher)
			where TObject : new()
		{
			TObject obj = (TObject)dispatcher.Invoke((Func<TObject>)(() => new TObject()));

			return obj;
		}
		public static void DispatcherAdd<TObject>(this ICollection<TObject> collection, TObject item)
		{
			Application.Current.Dispatcher.Invoke(
				(Action<TObject>)collection.Add,
				item
				);
		}
		public static void DispatcherBeginAdd<TObject>(this ICollection<TObject> collection, TObject item)
		{
			Application.Current.Dispatcher.BeginInvoke(
				(Action<TObject>)collection.Add,
				DispatcherPriority.Background,
				item
				);
		}
		public static void DispatcherAddRange<TObject>(this ICollection<TObject> collection, IEnumerable<TObject> items)
		{
			Application.Current.Dispatcher.Invoke(
				(Action<IEnumerable<TObject>>)((innerItems) =>
				{
					foreach (var item in items)
					{
						collection.Add(item);
					}
				}),
				DispatcherPriority.Background,
				items
				);
		}
		public static void DispatcherBeginAddRange<TObject>(this ICollection<TObject> collection, IEnumerable<TObject> items)
		{
			Application.Current.Dispatcher.BeginInvoke(
				(Action<IEnumerable<TObject>>)((innerItems) =>
				{
					foreach (var item in items)
					{
						collection.Add(item);
					}
				}),
				DispatcherPriority.Background,
				items
				);
		}
		public static bool DispatcherRemove<TObject>(this ICollection<TObject> collection, TObject item)
		{
			return (bool)Application.Current.Dispatcher.Invoke(
				(Func<TObject, bool>)collection.Remove,
				item
				);
		}
		public static void DispatcherBeginRemove<TObject>(this ICollection<TObject> collection, TObject item)
		{
			Application.Current.Dispatcher.BeginInvoke(
				(Func<TObject, bool>)collection.Remove,
				item
				);
		}
		public static void DispatcherClear<TObject>(this ICollection<TObject> collection)
		{
			Application.Current.Dispatcher.Invoke(
				(Action)collection.Clear
				);
		}
		public static void DispatcherBeginClear<TObject>(this ICollection<TObject> collection)
		{
			Application.Current.Dispatcher.BeginInvoke(
				(Action)collection.Clear,
				DispatcherPriority.Background
				);
		}
	}
}
